class SiteHeartBeatDailyStat < ActiveRecord::Base
  
  belongs_to :site_health_setting,
    :class_name => 'UserToolSetting::SiteHealth'

  belongs_to :the_fastest_heart_beat,
    :class_name => 'SiteHeartBeat::Available'

  belongs_to :the_slowest_heart_beat,
    :class_name => 'SiteHeartBeat::Available'

  has_many :availables,
    :foreign_key => :site_heart_beat_daily_stat_id,
    :class_name => 'SiteHeartBeat::Available'

  has_many :unavailables,
    :foreign_key => :site_heart_beat_daily_stat_id,
    :class_name => 'SiteHeartBeat::Unavailable'

  has_many :site_heart_beats, :order => 'created_at desc', :dependent => :destroy
  
  validates_presence_of :site_health_setting_id,
    :created_on
  validates_uniqueness_of :created_on,:scope => :site_health_setting_id

  def reset_available_site_heart_beats_count!
    update_attribute! :available_site_heart_beats_count, availables.size
  end

  def health_degree
    available_site_heart_beats_count * 100/ (available_site_heart_beats_count + unavailable_site_heart_beats_count)
  end

  def avg_response_time
    response_time  / (available_site_heart_beats_count + unavailable_site_heart_beats_count)
  end

  def take_pulses_count
    available_site_heart_beats_count + unavailable_site_heart_beats_count
  end
  
  def reset_unavailables_stat!
    update_attributes! :unavailable_site_heart_beats_count => unavailables.size
  end

  def reset_availables_stat!
    update_attributes! :available_site_heart_beats_count => availables.size,
      :response_time => SiteHeartBeat::Available.sum(:response_time,
        :conditions => ['site_heart_beat_daily_stat_id = ? ', id]
      ),
      :the_fastest_heart_beat => SiteHeartBeat::Available.find_by_site_heart_beat_daily_stat_id(        
        id,
        :order => 'response_time asc'
      ),
     :the_slowest_heart_beat => SiteHeartBeat::Available.find_by_site_heart_beat_daily_stat_id(
      id,
      :order => 'response_time desc'
    )
  end
end
